<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <tree-table
        class="tree-table"
        :data="catelist"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            style="color: lightgreen;"
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i style="color: red;" class="el-icon-error" v-else></i>
        </template>

        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" v-if="scope.row.cat_level === 1" type="success"
            >二级</el-tag
          >
          <el-tag size="mini" v-if="scope.row.cat_level === 2" type="warning"
            >三级</el-tag
          >
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            @click="showEditCateDialog(scope.row)"
            size="mini"
            icon="el-icon-edit"
            type="primary"
            >编辑</el-button
          >
          <el-button
            @click="toDeleteCate(scope.row.cat_id)"
            size="mini"
            icon="el-icon-delete"
            type="danger"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 7, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="closeCateDialog"
    >
      <el-form
        :rules="addCateFormRules"
        ref="addCateFormRef"
        :model="addCateForm"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!--  checkStrictly: true为 change-on-selec的替代方法-->
          <el-cascader
            clearable
            v-model="selectKeys"
            :options="parentCateList"
            :props="{
              checkStrictly: true,
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children'
            }"
            @change="parentCateChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="closeEditCateDialog"
    >
      <el-form
        :rules="addCateFormRules"
        ref="editCateFormRef"
        :model="editCateForm"
        label-width="80px"
      >
        <el-form-item prop="cat_name" label="分类名称">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toeditCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 底部 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类数据
      catelist: [],
      total: 0,
      //   表格列定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          width: '400px'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      // 添加分类对话框隐藏与显示
      addCateDialogVisible: false,
      // 添加分类表单数据
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      // 表单校验规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 获取父级数据列表，【1，2】级
      parentCateList: [],
      // 添加分类对话框中选中的父级分类的id数组
      selectKeys: [],
      // 编辑使用
      editCateForm: {},
      editCateDialogVisible: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分类数据获取失败')
      }
      this.catelist = res.data.result
      this.total = res.data.total
    },
    // 监听每页大小的变化
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听页数
    handleCurrentChange(newNum) {
      this.queryInfo.pagenum = newNum
      this.getCateList()
    },
    showCateDialog() {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    // 分类添加对话框关闭前的初始化
    closeCateDialog() {
      this.$refs.addCateFormRef.resetFields()
      this.selectKeys = []
      // 父级分类id
      this.addCateForm.cat_pid = 0
      //  当前分类的等级
      this.addCateForm.cat_level = 0
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类列表数据失败')
      }
      this.parentCateList = res.data
    },
    // 监听添加分类下拉框的数据
    parentCateChange() {
      if (this.selectKeys.length > 0) {
        // 父级分类id
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        //  当前分类的等级
        this.addCateForm.cat_level = this.selectKeys.length
      } else {
        // 选择后又清空
        // 父级分类id
        this.addCateForm.cat_pid = 0
        //  当前分类的等级
        this.addCateForm.cat_level = 0
      }
      //  console.log(this.addCateForm)
    },
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }
        this.$message.success('添加分类成功')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    // 删除分类
    async toDeleteCate(id) {
      const confirmReturn = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmReturn !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败')
      }
      this.$message.success('删除分类成功')
      this.getCateList()
    },
    showEditCateDialog(row) {
      this.editCateDialogVisible = true
      this.editCateForm = row
    },
    closeEditCateDialog() {
      this.$refs.editCateFormRef.resetFields()
    },
    toeditCate() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`categories/${this.editCateForm.cat_id}`, {
          cat_name: this.editCateForm.cat_name
        })
        if (res.meta.status !== 200) {
          return this.$message.error('分类名称修改失败')
        }
        this.$message.success('分类名称修改成功')
        this.getCateList()
        this.editCateDialogVisible = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
.tree-table {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
